package com.zjs.vueRole.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zjs.config.Result;
import com.zjs.vueMenu.entity.VueMenu;
import com.zjs.vueRole.entity.RoleQuery;
import com.zjs.vueRole.entity.VueRole;
import com.zjs.vueRole.service.VueRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zjs
 * @since 2020-07-06
 */
@RestController
@RequestMapping("/vueRole")
public class VueRoleController {

    @Autowired
    private VueRoleService roleService;

    @GetMapping("/roleList")
    public Result<?> roleList(RoleQuery query){
        IPage<VueRole> page = roleService.page(new Page<>(query.getCurrent(), query.getSize()),
                new QueryWrapper<VueRole>().lambda().like(StrUtil.isNotBlank(query.getRoleName()), VueRole::getRoleName, query.getRoleName()));
        return Result.ok(page);
    }

    @GetMapping("/allRoles")
    public Result<?> allRoles(){
        return Result.ok(roleService.list(null));
    }


    /**
     * 获取当前角色权限，分层展示
     * @param id 角色id
     */
    @GetMapping("/getRoleMenuById")
    public Result<?> getRoleMenuById(Long id){
        VueRole role = roleService.getRoleMenuById(id);
        return Result.ok(role);
    }

    /**
     * 获取所有角色权限，分层展示
     * @param
     */
    @GetMapping("/getAllMenus")
    public Result<?> getAllMenus(){
        List<VueMenu> list = roleService.getAllMenus();
        return Result.ok(list);
    }

    /**
     * 修改当前角色权限，即关联的菜单（也包括按钮等）
     * @param id 角色id
     * @param menuIds  要保存的菜单id数组
     * @return
     */
    @PostMapping("/updateRoleMenus")
    public Result<?> updateRoleMenus(HttpServletRequest request, Long id,String menuIds) {
        try {
            roleService.updateRoleMenus(id,menuIds);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
        return Result.ok("操作成功");
    }

    @PostMapping("/addRole")
    public Result<?> addRole(HttpServletRequest request, VueRole role) {
        VueRole one = roleService.getOne(new QueryWrapper<VueRole>().lambda().eq(VueRole::getRoleName, role.getRoleName()));
        if(one != null){
            return Result.error("已添加过该角色");
        }
        roleService.save(role);
        return Result.ok("操作成功");
    }
}

